package com.webank.webase.chain.mgr.repository.mapper;

import com.webank.webase.chain.mgr.node.entity.NodeParam;
import com.webank.webase.chain.mgr.repository.bean.TbNode;
import com.webank.webase.chain.mgr.repository.bean.TbNodeExample;
import com.webank.webase.chain.mgr.repository.bean.TbNodeExample.Criteria;
import com.webank.webase.chain.mgr.repository.bean.TbNodeExample.Criterion;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import java.util.List;
import java.util.Map;

public class TbNodeSqlProvider {

    public String update(TbNode tbNode) {
        SQL sql = new SQL();
        sql.UPDATE("tb_node");
        sql.SET("modify_time=NOW()");
        if (tbNode.getBlockNumber() != null) {
            sql.SET("block_number = #{blockNumber}");
        }
        if (tbNode.getPbftView() != null) {
            sql.SET("pbft_view = #{pbftView}");
        }
        if (StringUtils.isNotBlank(tbNode.getDescription())) {
            sql.SET("description = #{description}");
        }
        if (tbNode.getNodeActive() != null) {
            sql.SET("node_active = #{nodeActive}");
        }
        sql.WHERE("node_id=#{nodeId} and group_id=#{groupId}");
        return sql.toString();
    }

    public String selectByParam(NodeParam param) {
        SQL sql = new SQL();
        sql.SELECT(ALL_COLUMN_FIELDS).FROM("tb_node");
        this.applyNodeParam(sql, param);
        if (param.getStart() != null && param.getPageSize() != null) {
            return String.format("%s limit #{start},#{pageSize}", sql.toString());
        }
        return sql.toString();
    }

    public String countByParam(NodeParam param) {
        SQL sql = new SQL();
        sql.SELECT("count(1)").FROM("tb_node");
        this.applyNodeParam(sql, param);
        return sql.toString();
    }

    public SQL applyNodeParam(SQL sql, NodeParam param) {
        if (param.getChainId() != null) {
            sql.WHERE("chain_id = #{chainId}");
        }
        if (param.getGroupId() != null) {
            sql.WHERE("group_id = #{groupId}");
        }
        if (StringUtils.isNotBlank(param.getNodeId())) {
            sql.WHERE("node_id = #{nodeId}");
        }
        if (param.getP2pPort() != null) {
            sql.WHERE("p2p_port = #{p2pPort}");
        }
        if (StringUtils.isNotBlank(param.getNodeIp())) {
            sql.WHERE("node_ip = #{nodeIp}");
        }
        if (StringUtils.isNotBlank(param.getFlagSortedByTime())) {
            sql.ORDER_BY(String.format("modify_time %s", param.getFlagSortedByTime()));
        }
        if (CollectionUtils.isNotEmpty(param.getNodeIds())) {
            String whereSql = StringUtils.join(param.getNodeIds(), ",").replaceAll(",", "','");
            sql.WHERE(String.format("node_id in('%s')", whereSql));
        }
        return sql;
    }

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public static final String ALL_COLUMN_FIELDS = "node_id,chain_id,group_id,node_name,node_type,node_ip,p2p_port,block_number,pbft_view,node_active,description,create_time,modify_time";

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String countByExample(TbNodeExample example) {
        SQL sql = new SQL();
        sql.SELECT("count(*)").FROM("tb_node");
        applyWhere(sql, example, false);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String deleteByExample(TbNodeExample example) {
        SQL sql = new SQL();
        sql.DELETE_FROM("tb_node");
        applyWhere(sql, example, false);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String insertSelective(TbNode record) {
        SQL sql = new SQL();
        sql.INSERT_INTO("tb_node");
        if (record.getNodeId() != null) {
            sql.VALUES("node_id", "#{nodeId,jdbcType=VARCHAR}");
        }
        if (record.getChainId() != null) {
            sql.VALUES("chain_id", "#{chainId,jdbcType=INTEGER}");
        }
        if (record.getGroupId() != null) {
            sql.VALUES("group_id", "#{groupId,jdbcType=INTEGER}");
        }
        if (record.getNodeName() != null) {
            sql.VALUES("node_name", "#{nodeName,jdbcType=VARCHAR}");
        }
        if (record.getNodeType() != null) {
            sql.VALUES("node_type", "#{nodeType,jdbcType=VARCHAR}");
        }
        if (record.getNodeIp() != null) {
            sql.VALUES("node_ip", "#{nodeIp,jdbcType=VARCHAR}");
        }
        if (record.getP2pPort() != null) {
            sql.VALUES("p2p_port", "#{p2pPort,jdbcType=INTEGER}");
        }
        if (record.getBlockNumber() != null) {
            sql.VALUES("block_number", "#{blockNumber,jdbcType=BIGINT}");
        }
        if (record.getPbftView() != null) {
            sql.VALUES("pbft_view", "#{pbftView,jdbcType=BIGINT}");
        }
        if (record.getNodeActive() != null) {
            sql.VALUES("node_active", "#{nodeActive,jdbcType=TINYINT}");
        }
        if (record.getDescription() != null) {
            sql.VALUES("description", "#{description,jdbcType=VARCHAR}");
        }
        if (record.getCreateTime() != null) {
            sql.VALUES("create_time", "#{createTime,jdbcType=TIMESTAMP}");
        }
        if (record.getModifyTime() != null) {
            sql.VALUES("modify_time", "#{modifyTime,jdbcType=TIMESTAMP}");
        }
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String selectByExample(TbNodeExample example) {
        SQL sql = new SQL();
        if (example != null && example.isDistinct()) {
            sql.SELECT_DISTINCT("node_id");
        } else {
            sql.SELECT("node_id");
        }
        sql.SELECT("chain_id");
        sql.SELECT("group_id");
        sql.SELECT("node_name");
        sql.SELECT("node_type");
        sql.SELECT("node_ip");
        sql.SELECT("p2p_port");
        sql.SELECT("block_number");
        sql.SELECT("pbft_view");
        sql.SELECT("node_active");
        sql.SELECT("description");
        sql.SELECT("create_time");
        sql.SELECT("modify_time");
        sql.FROM("tb_node");
        applyWhere(sql, example, false);
        if (example != null && example.getOrderByClause() != null) {
            sql.ORDER_BY(example.getOrderByClause());
        }
        // add pagination for mysql with limit clause 
        StringBuilder sqlBuilder = new StringBuilder(sql.toString());
        if (example != null && (example.getStart() > -1 || example.getCount() > -1)) {
            sqlBuilder.append(" limit ");
            if (example.getStart() > -1 && example.getCount() > -1) {
                sqlBuilder.append(example.getStart()).append(",").append(example.getCount());
            } else if (example.getStart() > -1) {
                sqlBuilder.append(example.getStart());
            } else if (example.getCount() > -1) {
                sqlBuilder.append(example.getCount());
            }
        }
        return sqlBuilder.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String updateByExampleSelective(Map<String, Object> parameter) {
        TbNode record = (TbNode) parameter.get("record");
        TbNodeExample example = (TbNodeExample) parameter.get("example");
        SQL sql = new SQL();
        sql.UPDATE("tb_node");
        if (record.getNodeId() != null) {
            sql.SET("node_id = #{record.nodeId,jdbcType=VARCHAR}");
        }
        if (record.getChainId() != null) {
            sql.SET("chain_id = #{record.chainId,jdbcType=INTEGER}");
        }
        if (record.getGroupId() != null) {
            sql.SET("group_id = #{record.groupId,jdbcType=INTEGER}");
        }
        if (record.getNodeName() != null) {
            sql.SET("node_name = #{record.nodeName,jdbcType=VARCHAR}");
        }
        if (record.getNodeType() != null) {
            sql.SET("node_type = #{record.nodeType,jdbcType=VARCHAR}");
        }
        if (record.getNodeIp() != null) {
            sql.SET("node_ip = #{record.nodeIp,jdbcType=VARCHAR}");
        }
        if (record.getP2pPort() != null) {
            sql.SET("p2p_port = #{record.p2pPort,jdbcType=INTEGER}");
        }
        if (record.getBlockNumber() != null) {
            sql.SET("block_number = #{record.blockNumber,jdbcType=BIGINT}");
        }
        if (record.getPbftView() != null) {
            sql.SET("pbft_view = #{record.pbftView,jdbcType=BIGINT}");
        }
        if (record.getNodeActive() != null) {
            sql.SET("node_active = #{record.nodeActive,jdbcType=TINYINT}");
        }
        if (record.getDescription() != null) {
            sql.SET("description = #{record.description,jdbcType=VARCHAR}");
        }
        if (record.getCreateTime() != null) {
            sql.SET("create_time = #{record.createTime,jdbcType=TIMESTAMP}");
        }
        if (record.getModifyTime() != null) {
            sql.SET("modify_time = #{record.modifyTime,jdbcType=TIMESTAMP}");
        }
        applyWhere(sql, example, true);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String updateByExample(Map<String, Object> parameter) {
        SQL sql = new SQL();
        sql.UPDATE("tb_node");
        sql.SET("node_id = #{record.nodeId,jdbcType=VARCHAR}");
        sql.SET("chain_id = #{record.chainId,jdbcType=INTEGER}");
        sql.SET("group_id = #{record.groupId,jdbcType=INTEGER}");
        sql.SET("node_name = #{record.nodeName,jdbcType=VARCHAR}");
        sql.SET("node_type = #{record.nodeType,jdbcType=VARCHAR}");
        sql.SET("node_ip = #{record.nodeIp,jdbcType=VARCHAR}");
        sql.SET("p2p_port = #{record.p2pPort,jdbcType=INTEGER}");
        sql.SET("block_number = #{record.blockNumber,jdbcType=BIGINT}");
        sql.SET("pbft_view = #{record.pbftView,jdbcType=BIGINT}");
        sql.SET("node_active = #{record.nodeActive,jdbcType=TINYINT}");
        sql.SET("description = #{record.description,jdbcType=VARCHAR}");
        sql.SET("create_time = #{record.createTime,jdbcType=TIMESTAMP}");
        sql.SET("modify_time = #{record.modifyTime,jdbcType=TIMESTAMP}");
        TbNodeExample example = (TbNodeExample) parameter.get("example");
        applyWhere(sql, example, true);
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String updateByPrimaryKeySelective(TbNode record) {
        SQL sql = new SQL();
        sql.UPDATE("tb_node");
        if (record.getNodeName() != null) {
            sql.SET("node_name = #{nodeName,jdbcType=VARCHAR}");
        }
        if (record.getNodeType() != null) {
            sql.SET("node_type = #{nodeType,jdbcType=VARCHAR}");
        }
        if (record.getNodeIp() != null) {
            sql.SET("node_ip = #{nodeIp,jdbcType=VARCHAR}");
        }
        if (record.getP2pPort() != null) {
            sql.SET("p2p_port = #{p2pPort,jdbcType=INTEGER}");
        }
        if (record.getBlockNumber() != null) {
            sql.SET("block_number = #{blockNumber,jdbcType=BIGINT}");
        }
        if (record.getPbftView() != null) {
            sql.SET("pbft_view = #{pbftView,jdbcType=BIGINT}");
        }
        if (record.getNodeActive() != null) {
            sql.SET("node_active = #{nodeActive,jdbcType=TINYINT}");
        }
        if (record.getDescription() != null) {
            sql.SET("description = #{description,jdbcType=VARCHAR}");
        }
        if (record.getCreateTime() != null) {
            sql.SET("create_time = #{createTime,jdbcType=TIMESTAMP}");
        }
        if (record.getModifyTime() != null) {
            sql.SET("modify_time = #{modifyTime,jdbcType=TIMESTAMP}");
        }
        sql.WHERE("node_id = #{nodeId,jdbcType=VARCHAR}");
        sql.WHERE("chain_id = #{chainId,jdbcType=INTEGER}");
        sql.WHERE("group_id = #{groupId,jdbcType=INTEGER}");
        return sql.toString();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    protected void applyWhere(SQL sql, TbNodeExample example, boolean includeExamplePhrase) {
        if (example == null) {
            return;
        }
        String parmPhrase1;
        String parmPhrase1_th;
        String parmPhrase2;
        String parmPhrase2_th;
        String parmPhrase3;
        String parmPhrase3_th;
        if (includeExamplePhrase) {
            parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        } else {
            parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        }
        StringBuilder sb = new StringBuilder();
        List<Criteria> oredCriteria = example.getOredCriteria();
        boolean firstCriteria = true;
        for (int i = 0; i < oredCriteria.size(); i++) {
            Criteria criteria = oredCriteria.get(i);
            if (criteria.isValid()) {
                if (firstCriteria) {
                    firstCriteria = false;
                } else {
                    sb.append(" or ");
                }
                sb.append('(');
                List<Criterion> criterions = criteria.getAllCriteria();
                boolean firstCriterion = true;
                for (int j = 0; j < criterions.size(); j++) {
                    Criterion criterion = criterions.get(j);
                    if (firstCriterion) {
                        firstCriterion = false;
                    } else {
                        sb.append(" and ");
                    }
                    if (criterion.isNoValue()) {
                        sb.append(criterion.getCondition());
                    } else if (criterion.isSingleValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
                        } else {
                            sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j, criterion.getTypeHandler()));
                        }
                    } else if (criterion.isBetweenValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
                        } else {
                            sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
                        }
                    } else if (criterion.isListValue()) {
                        sb.append(criterion.getCondition());
                        sb.append(" (");
                        List<?> listItems = (List<?>) criterion.getValue();
                        boolean comma = false;
                        for (int k = 0; k < listItems.size(); k++) {
                            if (comma) {
                                sb.append(", ");
                            } else {
                                comma = true;
                            }
                            if (criterion.getTypeHandler() == null) {
                                sb.append(String.format(parmPhrase3, i, j, k));
                            } else {
                                sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
                            }
                        }
                        sb.append(')');
                    }
                }
                sb.append(')');
            }
        }
        if (sb.length() > 0) {
            sql.WHERE(sb.toString());
        }
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table tb_node
     *
     * @mbg.generated
     */
    public String getOneByExample(TbNodeExample example) {
        SQL sql = new SQL();
        if (example != null && example.isDistinct()) {
            sql.SELECT_DISTINCT("node_id");
        } else {
            sql.SELECT("node_id");
        }
        sql.SELECT("chain_id");
        sql.SELECT("group_id");
        sql.SELECT("node_name");
        sql.SELECT("node_type");
        sql.SELECT("node_ip");
        sql.SELECT("p2p_port");
        sql.SELECT("block_number");
        sql.SELECT("pbft_view");
        sql.SELECT("node_active");
        sql.SELECT("description");
        sql.SELECT("create_time");
        sql.SELECT("modify_time");
        sql.FROM("tb_node");
        applyWhere(sql, example, false);
        if (example != null && example.getOrderByClause() != null) {
            sql.ORDER_BY(example.getOrderByClause());
        }
        StringBuilder sqlBuilder = new StringBuilder(sql.toString());
        sqlBuilder.append(" limit 1 ");
        return sqlBuilder.toString();
    }
}
